// pages/personal-center/personal-center.js
const app = getApp()

Page({
  data: {
    userInfo: {},
    healthInfo: {},
    recipeHistory: [],
    collections: [],
    shoppingList: [],
    healthTrends: [],
    version: '1.0.0'
  },

  onLoad() {
    this.loadUserData()
  },

  onShow() {
    this.loadUserData()
  },

  loadUserData() {
    const userInfo = wx.getStorageSync('userInfo') || {}
    const healthInfo = wx.getStorageSync('healthInfo') || {}
    const recipeHistory = wx.getStorageSync('recipeHistory') || []
    const collections = wx.getStorageSync('recipeCollections') || []
    const shoppingList = wx.getStorageSync('shoppingList') || []

    this.setData({
      userInfo,
      healthInfo,
      recipeHistory,
      collections,
      shoppingList
    })
  },

  // 跳转到用户设置
  goToUserSetting() {
    wx.navigateTo({
      url: '/pages/user-setting/user-setting'
    })
  },

  // 查看历史记录
  viewRecipeHistory() {
    if (this.data.recipeHistory.length === 0) {
      wx.showModal({
        title: '提示',
        content: '暂无历史记录',
        showCancel: false
      })
      return
    }

    wx.showActionSheet({
      itemList: ['查看详细记录', '导出记录'],
      success: (res) => {
        if (res.tapIndex === 0) {
          this.showHistoryDetail()
        } else if (res.tapIndex === 1) {
          this.exportHistory()
        }
      }
    })
  },

  // 显示历史记录详情
  showHistoryDetail() {
    const history = this.data.recipeHistory
    let content = '最近7天食谱记录:\n\n'
    
    history.slice(0, 7).forEach(item => {
      content += `${item.date}:\n`
      content += `早餐: ${item.breakfast}\n`
      content += `午餐: ${item.lunch}\n`
      content += `晚餐: ${item.dinner}\n`
      content += `总热量: ${item.totalCalories} kcal\n\n`
    })

    wx.showModal({
      title: '历史记录',
      content: content,
      showCancel: false
    })
  },

  // 导出历史记录
  exportHistory() {
    wx.showModal({
      title: '导出记录',
      content: '此功能将在后续版本中实现',
      showCancel: false
    })
  },

  // 查看收藏
  viewCollections() {
    if (this.data.collections.length === 0) {
      wx.showModal({
        title: '提示',
        content: '暂无收藏的食谱',
        showCancel: false
      })
      return
    }

    const collectionNames = this.data.collections.map(item => 
      `${item.date} - ${item.name}`
    )

    wx.showActionSheet({
      itemList: collectionNames.slice(0, 5),
      success: (res) => {
        const selectedCollection = this.data.collections[res.tapIndex]
        this.showCollectionDetail(selectedCollection)
      }
    })
  },

  // 显示收藏详情
  showCollectionDetail(collection) {
    const recipe = collection.recipe
    let content = `${collection.name}\n`
    content += `收藏日期: ${collection.date}\n\n`
    content += `食材:\n`
    recipe.ingredients.forEach(ingredient => {
      content += `${ingredient.name} ${ingredient.amount}${ingredient.unit}\n`
    })
    content += `\n做法:\n`
    recipe.steps.forEach((step, index) => {
      content += `${index + 1}. ${step}\n`
    })

    wx.showModal({
      title: '收藏详情',
      content: content,
      showCancel: false
    })
  },

  // 查看购物清单
  viewShoppingList() {
    if (this.data.shoppingList.length === 0) {
      wx.showModal({
        title: '提示',
        content: '购物清单为空',
        showCancel: false
      })
      return
    }

    let content = '购物清单:\n\n'
    this.data.shoppingList.forEach(item => {
      const status = item.checked ? '✓' : '○'
      content += `${status} ${item.name} ${item.amount}${item.unit}\n`
      if (item.note) {
        content += `  备注: ${item.note}\n`
      }
    })

    wx.showModal({
      title: '购物清单',
      content: content,
      showCancel: false,
      confirmText: '确定'
    })
  },

  // 清除数据
  clearData() {
    wx.showModal({
      title: '确认清除',
      content: '确定要清除所有本地数据吗？此操作不可恢复。',
      success: (res) => {
        if (res.confirm) {
          // 清除所有本地存储数据
          wx.removeStorageSync('userInfo')
          wx.removeStorageSync('healthInfo')
          wx.removeStorageSync('foodList')
          wx.removeStorageSync('recipeHistory')
          wx.removeStorageSync('recipeCollections')
          wx.removeStorageSync('shoppingList')
          wx.removeStorageSync('lastRecipe')

          this.setData({
            userInfo: {},
            healthInfo: {},
            recipeHistory: [],
            collections: [],
            shoppingList: []
          })

          app.showSuccess('数据清除成功')
          
          // 跳转到登录页面
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/login/login'
            })
          }, 1500)
        }
      }
    })
  },

  // 退出登录
  logout() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除用户相关数据
          wx.removeStorageSync('userInfo')
          wx.removeStorageSync('healthInfo')
          
          app.showSuccess('退出成功')
          
          // 跳转到登录页面
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/login/login'
            })
          }, 1500)
        }
      }
    })
  }
})